var searchName=null;
$(function () {

	$("#searchButton").click(function(){
		searchName = $("#searchName").val().trim();
		initdata();
	});
//	initdata();
	function initdata() {
		$.ajax({
	        url : ctx+"/area/listWeightData",
	        type:'GET',
	        async:false,
	        dataType : 'json',
	        data : {
	        	"name":searchName
	        },
	        success : function(result){
	        	$(".area_container").html("");
		    	var content="";
		    	$("#NoData").text("");
		    	if (result.length!=0) {
			    	$(result).each(function(index,area){
			        	content+="<form action='"+ctx+"/area/saveWeight' class='form-horizontal' method='post'>"+
				        			"<input type='hidden' name='id' value='"+area.id+"'>"+
				        			"<div class='col-md-12'>"+
				        				"<div class='panel panel-default'>"+
				        					"<div class='panel-heading'>"+
				        						"<span class='name_span'>"+area.name+"</span>"+
				        						"<input type='text' value='"+area.name+"' name='name' class='name_input' style='width:150px;display:none;' required/>"+
				        						"<button type='button' data='"+area.id+"' class='deleteArea pull-right button button-pill button-flat-caution button-tiny'><span class='glyphicon glyphicon-remove'></span>&nbsp;删除</button>"+
//				        						"<button type='button' class='area-add pull-right button button-pill button-flat-action button-tiny'><span class='glyphicon glyphicon-plus'></span>&nbsp;新增重量段</button>"+
				        						"<button type='button' class='area-edit pull-right button button-pill button-flat-primary button-tiny'><span class='glyphicon glyphicon-edit'></span>&nbsp;修改</button>"+
				        						"<button type='button' class='area-save pull-right button button-pill button-flat button-tiny'><span class='glyphicon glyphicon-floppy-disk'></span>&nbsp;保存</button>"+
				        					"</div>"+
				        					"<div class='panel-body  time_panel_body'>";
				        					if (area.chargeStartWeight != null && area.chargeStartWeight.length !=0) {
				        						var chargeStartWeight = area.chargeStartWeight;
				        						$(area.chargeStartWeight).each(function(time_index,time){
				        							content+=
				        								"<div class='item-length'>"+
				        								"<div class='panel-group'>"+
				        								  "<div class='panel panel-default'>"+
				        									"<div class='panel-heading'>"+
				        									  "<h4 class='panel-title'>"+
				        										"<a data-toggle='collapse' href='#collapseOne_"+time.id+"'>"+
				        										"展开  "+
				        										"</a>"+
//				        										"<span class='time_content'>"+
//				        										"<input type='number' value='"+time.cost+"' name='chargeStartWeight["+time_index+"].cost' data-name='chargeStartWeight["+time_index+"]' class='cost_input bottom_border' style='width:60px;display:none;' required min='0' />"+
//				        										"</span>" +
				        										"<span class='time_button pull-right'>"+
				        											"<button type='button' class='pull-right btn btn-default btn-xs time_button_delete'>删除</button>"+
				        											"<button type='button' class='pull-right btn btn-default btn-xs time_button_edit'>修改</button>"+
				        											"<button type='button' class='pull-right btn btn-default btn-xs time_button_add'>添加重量价格</button>"+
				        										"</span>"+
				        									  "</h4>"+
				        									"</div>"+
				        									"<div id='collapseOne_"+time.id+"' class='panel-collapse collapse in'>"+
				        									  "<div class='panel-body'>"+
				        										"<table class='table table-condensed table-bordered'>"+
				        											"<tr style='font-size:14px;'>"+
				        												"<th>开始重量(KG)</th>"+
				        												"<th>结束重量(KG)</th>"+
				        												"<th>增长价(元)</th>"+
				        												"<th>操作</th>"+
				        											"</tr>";
				        											if (time.chargeWeightDistance != null && time.chargeWeightDistance.size !=0) {
				        												var distancelist=time.chargeWeightDistance;
				        												$(distancelist).each(function(distance_index,distance){
			        													content+="<tr class='distance_tr'>";
				        													if (distance_index==0) {
			        														content+="<td>0</td>";
				        													}else {
			        														content+="<td><span>"+distancelist[distance_index-1].distance+"</span><input class='distance_td_distance_start' type='number' required  value='"+distancelist[distance_index-1].distance+"' style='display:none;' /></td>";
				        													}
				        													content+="<td><span>"+distance.distance+"</span><input class='distance_td_distance' type='number' required value='"+distance.distance+"' style='display:none;' /></td>"+
			        														"<td><span>"+distance.money+"</span><input class='distance_td_money' type='number' required value='"+distance.money+"' style='display:none;' /></td>"+
			        														"<td>"+
			        															"<a href='javascript:;' class='distance_td_edit'>修改</a>"+
			        															"<a href='javascript:;' class='distance_td_delete'>删除</a>"+
			        														"</td>"+
			        													"</tr>";
				        												});
				        											}
				        										content+="</table>"+
				        										"<hr/>"+
				        											"<span class='time_content2'>"+
				        											"超过（<span class='this_qblc'>"+time.startWeight+"</span><input type='number' value='"+time.startWeight+"' name='chargeStartWeight["+time_index+"].startWeight' class='qblc_input bottom_border' style='width:60px;display:none;' required min='0'/>KG）"+
				        											"以后每<span class='this_djglUnit'>"+time.addWeight+"</span><input type='number' value='"+time.addWeight+"' name='chargeStartWeight["+time_index+"].addWeight' class='djglUnit_input bottom_border' style='width:60px;display:none;' required min='0'/>KG"+
				        											"（不足<span class='this_djglThresholdt'>"+time.overWeight+"</span><input type='number' value='"+time.overWeight+"' name='chargeStartWeight["+time_index+"].overWeight' class='djglThresholdt_input bottom_border' style='width:60px;display:none;' required min='0'/>KG不计费）"+
				        											"加收<span class='this_djglCost'>"+time.cost+"</span><input type='number' value='"+time.cost+"' name='chargeStartWeight["+time_index+"].cost' data-name='chargeStartWeight["+time_index+"]' class='djglCost_input bottom_border' style='width:60px;display:none;' required min='0'/>元 ；"+ 
				        											"<p></p>"+
				        									  "</div>"+
				        									"</div>"+
				        								  "</div>"+
				        								"</div>"+
				        							"</div>";
				        						});
				        					}
			        	
				        					
			        				   content+="<h4 class='text-primary'>收费说明：</h4>"+
					        					"<p class='text-muted'>"+
					        					"<span class='memo_span'>"+area.memo+"</span>"+
					        					"<textarea class='memo_textarea' cols='100' rows='5' style='display:none;' name='memo'>"+area.memo+"</textarea>"+
					        					"</p>"+
				        					"</div>"+
				        				"</div>"+
		        					"</div>"+
				        			"</form>";
			    	});
			    	$(".area_container").append(content);
		    	} else {
		    		 $("#NoData").text("当前页面暂无记录 ");
		    	}
	        
	        }
	        
		});
	}
    $(document).on("click",".area-save",function (){
    	var thisform=$(this).parent().parent().parent().parent();
    	if($.trim(thisform.find(".name_input").val())==""){
    		alert("请填写收费标准名称");
    		thisform.find(".name_input").focus();
            return false;
    	}
    	
    	if(thisform.find(".item-length").length==0){
    		alert("至少添加一条重量区间段");
            return false;
    	}
    	
    	var formable=true;
    	
    	var numPoint=/^(\d+)(.[0-9]{0,2})?$/;
    	var numPoint2=/^(\d+)$/;
    	$(thisform).find(".item-length").each(function(index,element){
    		if($(element).find(".qblc_input").val()!="" && !numPoint.test($(element).find(".qblc_input").val())){
    			alert("重量格式不正确。");
    			$(element).find(".time_button_edit").click();
    			$(element).find(".qblc_input").focus();
    			formable=false;
    			return false;
    		}
    		
    		var last_end_distance=0;
    		$(element).find(".distance_tr").each(function(i,e){
    			var start_distance=$(e).find(".distance_td_distance_start").val();
        		var end_distance=$(e).find(".distance_td_distance").val();
        		var distance_money=$(e).find(".distance_td_money").val();
        		
        		if(!start_distance){
        			start_distance=0;
        		}
        		
        		if(start_distance!="" && !numPoint.test(start_distance)){
        			alert("开始里重量式不正确。");
        			$(e).find(".distance_td_edit").click();
        			$(e).find(".distance_td_distance_start").focus();
        			formable=false;
        			return false;
        		}
        		else if(end_distance!="" && !numPoint.test(end_distance)){
        			alert("结束重量格式不正确。");
        			$(e).find(".distance_td_edit").click();
        			$(e).find(".distance_td_distance").focus();
        			formable=false;
        			return false;
        		}
        		else if(distance_money!="" && !numPoint.test(distance_money)){
        			alert("增长价格式不正确。");
        			$(e).find(".distance_td_edit").click();
        			$(e).find(".distance_td_money").focus();
        			formable=false;
        			return false;
        		}
        		
        		if(parseFloat(start_distance)>parseFloat(end_distance)){
        			alert("结束重量必须大于开始重量");
        			$(element).find(".time_button_edit").click();
        			$(e).find(".distance_td_distance").focus();
        			formable=false;
        			return false;
        		}
        		
        		if(parseFloat(end_distance)>parseFloat(last_end_distance)){
        			last_end_distance=end_distance;
        		}
    		});
    		
    		if(!formable){
        		return false;
        	}
    		
    		if($(element).find(".distance_tr").length>0 && last_end_distance!=$(element).find(".qblc_input").val()){
        		alert("超出重量必须等于最大结束重量");
        		$(element).find(".time_button_edit").click();
        		$(element).find(".qblc_input").focus();
        		formable=false;
    			return false;
        	}
    		
    	});
    	
    	if(!formable){
    		return false;
    	}
    	
    	thisform.find(".item-length").each(function(index,element){
    		$(element).find(".distance_tr").each(function(i,e){
    			$(e).find(".distance_td_distance").attr("name",$(element).find(".djglCost_input").attr("data-name")+".chargeWeightDistance["+i+"].distance");
    			$(e).find(".distance_td_money").attr("name",$(element).find(".djglCost_input").attr("data-name")+".chargeWeightDistance["+i+"].money");
    		});
    	});
        $(thisform).find(".area-save").attr("disabled",true);
        $.post(thisform.attr("action"),thisform.serialize(),function(result){
			if(result.success){
				$.scojs_message(result.message, $.scojs_message.TYPE_OK);
				window.location.reload(true);
			}
			else{
				$.scojs_message(result.message, $.scojs_message.TYPE_ERROR);
				$(thisform).find(".area-save").attr("disabled",false);
			}
		});

    	return false;
    });


    $(document).on('click','.area-edit',function(){
    	$(this).parent().parent().find(".name_span").hide();
    	$(this).parent().parent().find(".name_input").show();
    	$(this).parent().parent().find(".memo_span").hide();
    	$(this).parent().parent().find(".memo_textarea").show();
    });
    
    //时间段删除
    $(document).on('click','.time_button_delete',function(){
    	$(this).parent().parent().parent().parent().parent().parent().remove();
    });
    
    //重量修改
    $(document).on('click','.time_button_edit',function(){
    	var table=$(this).parent().parent().parent().parent().find("table");
    	$(this).parent().parent().find(".time_content span").hide();
    	$(this).parent().parent().find(".time_content select").show();
    	$(this).parent().parent().find(".time_content input").show();
    	$(this).parent().parent().parent().parent().find(".time_content2 span").hide();
    	$(this).parent().parent().parent().parent().find(".time_content2 input").show();
    	
    	if(table.parent().parent().css("display")=="none"){
    		$(this).parent().parent().find("a").click();
    	}
    });
    
    //重量价格添加
    $(document).on('click','.time_button_add',function(){
    	var table=$(this).parent().parent().parent().parent().find("table");
    	var length=table.find(".distance_tr").length;
    	var content="";
    	content+="<tr class='distance_tr'>";
    	if(length==0){
    		content+="<td>0</td>";
    	}
    	else{
    		var value=table.find(".distance_tr:last").find(".distance_td_distance").val();
    		content+="<td><input class='distance_td_distance_start' type='number' min='0' required value='"+value+"' /></td>";
    	}
    	content+="<td><input class='distance_td_distance' type='number' min='0' required /></td>"+
				 "<td><input class='distance_td_money' type='number' min='0' required /></td>"+
				 "<td><a href='javascript:;' class='distance_td_delete'>删除</a></td>"+
				"</tr>";
    	table.find("tbody").append(content);
    	if(table.parent().parent().css("display")=="none"){
    		$(this).parent().parent().find("a").click();
    	}
    });
    
    //重量价格删除
    $(document).on('click','.distance_td_delete',function(){
    	$(this).parent().parent().remove();
    });
    
    //重量价格编辑
    $(document).on('click','.distance_td_edit',function(){
    	$(this).parent().parent().find("span").hide();
    	$(this).parent().parent().find("input").show();
    });
    
    //重量改变
    $(document).on('change','.distance_td_distance',function(){
    	if($(this).val() > 999999999){
    		alert("结束重量不能超过999999999")
    	}
    	$($(this).parent().parent().next().find("span")[0]).html($(this).val());
    	$(this).parent().parent().next().find(".distance_td_distance_start").val($(this).val());
    });
    
    $(document).on('click','.area-add',function(){
    	var currItemLength=$(this).parent().parent().find(".item-length").length;
    	var randomid=randomString(5);
    	var newitem = '<div class="item-length">'+
    					'<div class="panel-group">'+
						  '<div class="panel panel-default">'+
						    '<div class="panel-heading">'+
						      '<h4 class="panel-title">'+
//						        '<a data-toggle="collapse" href="#collapseOne_'+randomid+'">'+
//								'展开'+
//						        '</a>'+
						        "<span class='time_content' style='display:none;'>"+
								"<input type='number' value='0' name='chargeStartWeight["+currItemLength+"].cost' data-name='chargeStartWeight["+currItemLength+"]' class='cost_input bottom_border' style='width:60px;display:none;' required min='0'/>"+
								"</span>" +
					        	'<span class="time_button pull-right">'+
						      		'<button type="button" class="pull-right btn btn-default btn-xs time_button_delete">删除</button>'+
						      		'<button type="button" class="pull-right btn btn-default btn-xs time_button_edit">修改</button>'+
						      		'<button type="button" class="pull-right btn btn-default btn-xs time_button_add">添加重量价格</button>'+
						      	'</span>'+
						      '</h4>'+
							'</div>'+
							
							'<div id="collapseOne_'+randomid+'" class="panel-collapse collapse">'+
						      '<div class="panel-body">'+
						      	'<table class="table table-condensed table-bordered">'+
									'<tr style="font-size:14px;">'+
										'<th>开始重量(	KG)</th>'+
										'<th>结束重量(KG)</th>'+
										'<th>增长价(元)</th>'+
										'<th>操作</th>'+
									'</tr>'+
								'</table>'+
								'<hr/>'+
								'<span class="time_content2">'+
									'超过（<input type="number" value="0" name="chargeStartWeight['+currItemLength+'].startWeight" class="qblc_input bottom_border" style="width:60px;" required min="0"/>KG），'+
						        	'以后每<input type="number" value="0" name="chargeStartWeight['+currItemLength+'].addWeight" class="djglUnit_input bottom_border" style="width:60px;" required min="0"/>KG'+
						        	'（不足<input type="number" value="0" name="chargeStartWeight['+currItemLength+'].overWeight" class="djglThresholdt_input bottom_border" style="width:60px;" required min="0"/>KG不计费）'+
						        	'加收<input type="number" value="0" name="chargeStartWeight['+currItemLength+'].cost" data-name="chargeStartWeight['+currItemLength+']" class="djglCost_input bottom_border" style="width:60px;" required min="0"/>元；'+
						        	'<p></p>'+
						      	'</span>'+
						      '</div>'+
						    '</div>'+
						    
						  '</div>'+
						'</div>'+
		                
		            '</div>';
					        	
    	$(this).parent().parent().find(".time_panel_body").prepend(newitem);
    	$(this).parent().parent().find(".time_panel_body:first").find(".time_button_edit").click();
    	
    	currItemLength++;
    });
    
    $("#add-new-area").click(function(){
//    	$(this).attr("disabled",true);
    	var currItemLength=$(this).parent().parent().find(".item-length").length;
    	var randomid=randomString(5);
    	var newitem = '<form action="'+window.daijia.ctx+'/area/createWeight" class="form-horizontal" method="post">'+
						'<div class="col-md-12">'+
							'<div class="panel panel-default">'+
							  '<div class="panel-heading">'+
					              '<input type="text" name="name" class="name_input" style="width:150px;" required/>'+
					              '<button type="button" class="deleteArea-new pull-right button button-pill button-flat-caution button-tiny"><span class="glyphicon glyphicon-remove"></span>&nbsp;删除</button>'+
//					              '<button type="button" class="area-add pull-right button button-pill button-flat-action button-tiny"><span class="glyphicon glyphicon-plus"></span>&nbsp;新增重量段</button>'+
					              '<button type="submit" class="area-save pull-right button button-pill button-flat button-tiny"><span class="glyphicon glyphicon-floppy-disk"></span>&nbsp;保存</button>'+
					          '</div>'+
							  '<div class="panel-body time_panel_body">'+
							  
					        	'<div class="item-length">'+
			    					'<div class="panel-group">'+
									  '<div class="panel panel-default">'+
									    '<div class="panel-heading">'+
									      '<h4 class="panel-title">'+
									        '<a data-toggle="collapse" href="#collapseOne_'+randomid+'">'+
											'展开'+
									        '</a>'+
//									        "<span class='time_content' style='display:none;'>"+
//											"<input type='number' value='0' name='chargeStartWeight[0].cost' data-name='chargeStartWeight[0]' class='cost_input bottom_border' style='width:60px;display:none;'/>"+
//											"</span>" +
								        	'<span class="time_button pull-right">'+
									      		'<button type="button" class="pull-right btn btn-default btn-xs time_button_delete">删除</button>'+
									      		'<button type="button" class="pull-right btn btn-default btn-xs time_button_edit">修改</button>'+
									      		'<button type="button" class="pull-right btn btn-default btn-xs time_button_add">添加重量价格</button>'+
									      	'</span>'+
									      '</h4>'+
										'</div>'+
										
										'<div id="collapseOne_'+randomid+'" class="panel-collapse collapse">'+
									      '<div class="panel-body">'+
									      	'<table class="table table-condensed table-bordered">'+
												'<tr style="font-size:14px;">'+
													'<th>开始重量(KG)</th>'+
													'<th>结束重量(KG)</th>'+
													'<th>增长价(元)</th>'+
													'<th>操作</th>'+
												'</tr>'+
											'</table>'+
											'<hr/>'+
											'<span class="time_content2">'+
												'超过（<input type="number" value="0" name="chargeStartWeight[0].startWeight" class="qblc_input bottom_border" style="width:60px;" required min="0"/>KG），'+
									        	'以后每<input type="number" value="0" name="chargeStartWeight[0].addWeight" class="djglUnit_input bottom_border" style="width:60px;" required min="0"/>KG'+
									        	'（不足<input type="number" value="0" name="chargeStartWeight[0].overWeight" class="djglThresholdt_input bottom_border" style="width:60px;" required min="0"/>KG不计费）'+
									        	'加收<input type="number" value="0" name="chargeStartWeight[0].cost" data-name="chargeStartWeight['+currItemLength+']" class="djglCost_input bottom_border" style="width:60px;" required min="0"/>元；'+
									        	'<p></p>'+					
									      	'</span>'+
									      '</div>'+
									    '</div>'+
									    
									  '</div>'+
									'</div>'+
					                
					            '</div>'+
					            
					            '<h4 class="text-primary">收费说明：</h4>'+
					            '<p class="text-muted">'+
					        		'<textarea cols="100" rows="5" name="memo"></textarea>'+
					            '</p>'+
							  '</div>'+
							'</div>'+
						'</div>'+
						'</form>';
    	
    	$(".area_container").prepend(newitem);
    	
    	$(".area_container").find(".time_panel_body:first").find(".time_button_edit").click();
    	
    });
    
	$(document).on("keydown","body",function(){
		if(window.event.keyCode == 13){
			$("#searchButton").click();
		}
	});
    
});

function addZero(obj) {
	if (obj != null) {
		obj=parseInt(obj);
	}
	if (obj<=10) {
		obj="0"+obj;
	}
	return obj;
}

function deleteItem(btn){
	$(btn).parent().parent().remove();
}
function padZero(hourormin){
	if(hourormin.length==1){
		return "0"+hourormin;
	}
	else{
		return hourormin;
	}
}
function randomString(len){
	len = len || 32;
	var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
	var maxPos = $chars.length;
	var pwd = '';
	for (var i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

